package com.wocai.jrt.orgadmin.setting.action;

import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.vteba.utils.id.ObjectId;
import com.vteba.web.action.GenericAction;
import com.vteba.web.action.JsonBean;
import com.wocai.jrt.orgadmin.employee.model.Employee;
import com.wocai.jrt.orgadmin.employee.model.Org;
import com.wocai.jrt.orgadmin.employee.service.spi.EmployeeService;
import com.wocai.jrt.orgadmin.employee.service.spi.OrgService;
import com.wocai.jrt.orgadmin.setting.model.Setting;
import com.wocai.jrt.orgadmin.setting.service.spi.SettingService;
import com.wocai.jrt.orgadmin.utils.UserUtils;

/**
 * 设置控制器
 * @author yinlei
 * @date 2015-12-10 10:04:05
 */
@Controller
@RequestMapping("/setting")
public class SettingAction extends GenericAction<Setting> {
	private static final Logger LOGGER = LoggerFactory.getLogger(SettingAction.class);
	
	@Inject
	private SettingService settingServiceImpl;
	
	@Inject 
	private OrgService orgServiceImpl;
	
	@Inject 
	private EmployeeService employeeServiceImpl;
	
	/**
     * 获得设置List，初始化列表页。
     * @param model 参数
     * @return 设置List
     */
    @RequestMapping("/list")
    public String initial( Map<String, Object> maps) {
    	try {
    		Setting model = new Setting();
    		model.setOrgId(UserUtils.getOrgId());
    		List<Setting> list = settingServiceImpl.pagedList(model);
    		//如果该机构基础设置不存在则初始化pad基础设置
    		if (list.size() == 0) {
    			Setting setOffline = new Setting();
    			setOffline.setId(ObjectId.get().toString());
    			setOffline.setContent("是否开通线下支付");
    			setOffline.setOrgId(UserUtils.getOrgId());
    			setOffline.setKeyName("offlinePay");
    			setOffline.setKeyValue("1");
    			setOffline.setFlag(false);
    			settingServiceImpl.save(setOffline);
    			Setting setAskOffline = new Setting();
    			setAskOffline.setId(ObjectId.get().toString());
    			setAskOffline.setContent("是否需要申请开通");
    			setAskOffline.setOrgId(UserUtils.getOrgId());
    			setAskOffline.setKeyName("askForOfflinePay");
    			setAskOffline.setKeyValue("1");
    			setAskOffline.setFlag(false);
    			settingServiceImpl.save(setAskOffline);
    			maps.put("offlinePay", true); 
    			maps.put("askForOfflinePay", true); 
    		} else {
    			for (Setting setting : list) {
    				if("1".equals(setting.getKeyValue())){
    					maps.put(setting.getKeyName(), true);
    				}else{
    					maps.put(setting.getKeyName(), false); 
    				}
    			}
    			Org org = orgServiceImpl.get(UserUtils.getOrgId());
    			maps.put("org", org);
    			String employeeId = org.getDefaultEmployeeId();
    			if (! StringUtils.isBlank(employeeId)) {
    				maps.put("employee", employeeServiceImpl.get(employeeId));
    			}
			}
		} catch (Exception e) {
			LOGGER.error("get record list error, errorMsg=[{}].", e.getMessage());
			return "common/error";
		}
        return "setting/setting";
    }
    
    /**
     * 更新设置信息
     * @param model 要更新的设置信息，含有ID
     * @return 操作结果信息
     */
    @ResponseBody
    @RequestMapping("/update")
    public JsonBean update(@RequestBody Setting model) {
    	JsonBean bean = new JsonBean();
    	try { 
    		Setting sets = new Setting();
    		sets.setOrgId(UserUtils.getOrgId());
    		sets.setKeyName(model.getKeyName());
    		List<Setting> list = settingServiceImpl.pagedList(sets);
    		if(list.size() != 1){
    			 bean.setMessage(ERROR);
                 bean.setCode(1);
                 LOGGER.info("update setting record error due to setting size.");
                 return bean;
    		}
    		Setting set = new Setting();
    		set.setId(list.get(0).getId());
    		set.setKeyValue(model.getKeyValue());
    		int result = settingServiceImpl.updateById(set);
            if (result == 1) {
                bean.setMessage(SUCCESS);
                bean.setCode(1);
                LOGGER.info("update setting record success.");
            } else {
                bean.setMessage(ERROR);
                LOGGER.error("update setting record error.");
            }
		} catch (Exception e) {
			LOGGER.error("update record error, errorMsg=[{}].", e.getMessage());
			bean.setMessage(ERROR);
		}
        return bean;
    }
    
    @ResponseBody
    @RequestMapping("/setDefaultEmployee")
    public JsonBean setDefaultEmployee(@RequestBody Employee employee){
    	JsonBean json = new JsonBean();
    	String employeeId = employee.getEmployeeId();
    	if (StringUtils.isBlank(employeeId)) {
    		json.setCode(0);
    		json.setMessage("请正确输入关键字搜索选取理财师");
    		return json;
    	}
    	try {
			Org o = orgServiceImpl.get(UserUtils.getOrgId());
			o.setDefaultEmployeeId(employeeId);
			int result = orgServiceImpl.updateById(o);
			if(1 > result){
				json.setCode(0);
				json.setMessage("更新机构信息失败");
				return json;
			}
			json.setCode(1);
			json.setMessage(SUCCESS);
		} catch (Exception e) {
			json.setCode(0);
			json.setMessage("服务器出了点小差，请稍后重试");
			return json;
		}
    	return json;
    }
    
}
